package com.shijie.controller.app;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.shijie.component.AppUserService;
import com.shijie.core.Result;
import com.shijie.core.ResultGenerator;
import com.shijie.core.annotation.NoLogin;
import com.shijie.domain.entity.Users;
import com.shijie.domain.vo.BaseUserVo;
import com.shijie.service.UsersService;
import me.chanjar.weixin.common.exception.WxErrorException;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/*
 *  @author: smart boy
 *  @date: 2018-08-06
 */
@RestController
@RequestMapping("/app/users")
public class AppUsersController {

    @Resource
    private UsersService usersService;

    @Resource
    private AppUserService appUserService;

    /**
     * 登录
     */
    @GetMapping(value = "/login")
    @NoLogin
    public Result login(@RequestParam String code) throws WxErrorException {
        Users user = usersService.login(code);
        String token = appUserService.createUserToken(new BaseUserVo(user));
        return ResultGenerator.success().putData("token", token).putData("user", user);
    }

    @GetMapping
    public Result list(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer pageSize) {
        PageHelper.startPage(page, pageSize);
        List<Users> list = usersService.selectAll();
        PageInfo<Users> pageInfo = new PageInfo<>(list);
        return ResultGenerator.success(pageInfo);
    }

    @PutMapping
    public Result update(@RequestBody Users users) {
        usersService.update(users);
        return ResultGenerator.success();
    }

    @GetMapping(value = "/detail")
    public Result detail(@RequestParam(required = false) String nickName, @RequestParam(required = false) Integer sex,
                         @RequestParam(required = false) String avatar) {
        Users users = usersService.updateUser(nickName, avatar, sex, appUserService.getCurrentUser());
        return ResultGenerator.success(users);
    }
}

